<?php
namespace app\providers\command;

use think\console\Input;
use think\console\Output;
use think\console\Command;
use think\console\input\Option;
use think\facade\Db;

// 命令  php think migrate:refresh --seed 

class MigrateRefreshCommand extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('migrate:refresh');
        $this->addOption('seed', null, Option::VALUE_NONE, 'seed');
        // 设置描述
        $this->setDescription('刷新数据结构');
    }

    protected function execute(Input $input, Output $output)
    {
        $tableSchema = env('DATABASE_DATABASE');
        //清空所有表
        $tables = Db::query("
            SELECT concat('DROP TABLE IF EXISTS ', table_name) delsql 
            FROM information_schema.tables 
            WHERE table_schema = '$tableSchema'
        ");
        foreach($tables as $table){
            $tables = Db::query($table['delsql']);
        }
        //重新建表
        exec("php think migrate:run");
        //根据需要重载入数据
        if( $input->hasOption('seed') ){
            exec("php think seed:run");
        }
        // 
        $output->writeln('----------------------------------------------------------------------');
        $output->writeln('数据库初始化成功!');
        $output->writeln('----------------------------------------------------------------------');
    }
}



